<?php

namespace App\Listeners;

use App\Events\UserLoginIn;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Redis;
use App\Models\API\Notification;
use App\Models\API\ChatMessage;

class UserLoginInEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserLoginIn  $event
     * @return void
     */
    public function handle(UserLoginIn $event)
    {
        $userId = $event->userId;
        
        $channel = 'notification-'.$userId;

        $notifications = Notification::where([
            ['status', 0],
            ['user_id', $userId]
        ])->count();

        // 私信
        $messages = ChatMessage::where([
            ['status', 0],
            ['companion_id', $userId]
        ])->count();

        $arr = [
            'type'   => 'push_notifications',
            'notifications' => $notifications,
            'messages' => $messages
        ];
        
        Redis::publish($channel, json_encode($arr));
    }
}
